package com.liss.lissaiagent.demo.invoke;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/*
* http调用ai
* */
public class DashScopeClient {
    
    public static void main(String[] args) {
        // API 密钥，请替换为您的实际密钥
        String apiKey =TestApiKey.API_KEY;
        if (apiKey == null || apiKey.isEmpty()) {
            System.err.println("请设置环境变量 DASHSCOPE_API_KEY");
            return;
        }
        
        // 构建请求 URL
        String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
        
        // 构建请求体
        JSONObject requestBody = JSONUtil.createObj()
            .set("model", "qwen-plus")
            .set("input", JSONUtil.createObj()
                .set("messages", JSONUtil.createArray()
                    .put(JSONUtil.createObj()
                        .set("role", "system")
                        .set("content", "You are a helpful assistant."))
                    .put(JSONUtil.createObj()
                        .set("role", "user")
                        .set("content", "你好，我是一名java程序员，我正在编写ai超级智能体"))
                ))
            .set("parameters", JSONUtil.createObj()
                .set("result_format", "message"));
        
        // 发送请求
        try (HttpResponse response = HttpRequest.post(url)
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .body(requestBody.toString())
                .timeout(60000) // 设置超时时间为60秒
                .execute()) {
            
            // 处理响应
            int status = response.getStatus();
            String result = response.body();
            
            System.out.println("状态码: " + status);
            System.out.println("响应内容: " + result);
            
            // 如果需要解析JSON响应
            if (status == 200) {
                JSONObject jsonResult = JSONUtil.parseObj(result);
                // 根据实际响应结构获取内容
                if (jsonResult.containsKey("output")) {
                    JSONObject output = jsonResult.getJSONObject("output");
                    if (output.containsKey("choices")) {
                        String content = output.getJSONArray("choices")
                                .getJSONObject(0)
                                .getJSONObject("message")
                                .getStr("content");
                        System.out.println("AI回复: " + content);
                    }
                }
            } else {
                System.err.println("请求失败: " + result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}